package com.hafu.dao;

import com.hafu.model.RuKuMain;
import com.hafu.util.DbUtil;
import com.hafu.util.StringUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class RuKuMainDao {
    public int addRuKuMain(RuKuMain rukuMain, Connection coon) throws SQLException{
        String sql = "insert into ruku_main(ruku_name,price,gys_name,rk_date) values(?,?,?,current_timestamp)";
        PreparedStatement preparedStatement = coon.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1, rukuMain.getRukuName());
        preparedStatement.setBigDecimal(2, rukuMain.getPrice());
        preparedStatement.setString(3, rukuMain.getGysName());
        int i = preparedStatement.executeUpdate();
        if (i > 0) {
            ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
            generatedKeys.next();
            return generatedKeys.getInt(1);
        }else {
            return -1;
        }
    }
    public ArrayList<RuKuMain>geRuKuMainByName(RuKuMain ruku){
        Connection coon= DbUtil.getConn();
        String sql="select * from ruku_main";
        if (!StringUtil.isEmpty(ruku.getRukuName())){
            sql=sql+" where ruku_name like '%"+ruku.getRukuName()+"%'";
        }
        ArrayList<RuKuMain> list=new ArrayList<>();
        try{
            PreparedStatement preparedStatement = coon.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                RuKuMain ruKuMain=new RuKuMain();
                ruKuMain.setId(resultSet.getInt("id"));
                ruKuMain.setRukuName(resultSet.getString("ruku_name"));
                ruKuMain.setPrice(resultSet.getBigDecimal("price"));
               ruKuMain.setGysName(resultSet.getString("gys_name"));
               ruKuMain.setRukuDate(resultSet.getString("rk_date"));
               list.add(ruKuMain);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }return list;
    }public boolean updateRuKu(RuKuMain rukuMain) {
        Connection coon = DbUtil.getConn();
        String sql = "update ruku_main set ruku_name=? where id=?";
        try {
            PreparedStatement preparedStatement = coon.prepareStatement(sql);
            preparedStatement.setString(1, rukuMain.getRukuName());
            preparedStatement.setInt(2, rukuMain.getId());
            int i=preparedStatement.executeUpdate();
            if(i>0){
                return true;
            }else return false;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }return false;

    }
}
